/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.dailyexpress.requestprocess2;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class MessageIdCache {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final ConcurrentHashMap<Long, String> messageIdMap;
    
    private MessageIdCache() {
        messageIdMap = new ConcurrentHashMap<Long, String>();
    }
    
    public static MessageIdCache getInstance() {
        return MessageIdCacheHolder.INSTANCE;
    }
    
    private static class MessageIdCacheHolder {
        
        private static final MessageIdCache INSTANCE = new MessageIdCache();
    }
    
    public synchronized String getBscList(Long messageId) {
        return messageIdMap.get(messageId);
    }
    
    public synchronized Long put(String bsc) {
        boolean containsKey = true;
        long messageId = 0;
        while(containsKey){
            messageId = new Date().getTime();
            containsKey = messageIdMap.containsKey(messageId);
            try {
                Thread.sleep(5);
            } catch (InterruptedException ex) {
                logger.error("", ex);
            }
        }
        
        logger.debug("Putting to MessageIdCache: [{} - {}]", messageId, bsc);
        messageIdMap.put(messageId, bsc);
        return messageId;
        
    }
    
    @Deprecated
    public synchronized String putMessageId(Long messageId, String bsc) {
        logger.debug("Putting put MessageIdCache: [{} - {}]", messageId, bsc);
        String result = messageIdMap.put(messageId, bsc);
        logger.debug("Cache size after put: {}", messageIdMap.size());
        return result;
    }
    
    public synchronized String remove(Long messageId) {
        logger.debug("Removing from MessageIdCache: [{}]", messageId);
        String result = messageIdMap.remove(messageId);
        logger.debug("Cache size after remove: {}", messageIdMap.size());
        return result;
    }
}
